package com.yihu.cms.action;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.cms.util.Osslog;
import com.yihu.cms.util.QRCodeUtil;
import com.yihu.web.bean.Artwork;
import com.yihu.web.bean.vo.ArtworkQrcodeVO;
import com.yihu.web.bean.vo.GridFsUser;
import com.yihu.web.bean.vo.QRCode;
import com.yihu.web.bean.vo.QrCodeQuery;
import com.yihu.web.utils.PropertiesUtil;
import com.yihu.yihuds.service.YihuUserService;

/**
 * 
 * @author Aaron
 *
 */
@Controller
@SuppressWarnings("rawtypes")
public class QRCodeController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	YihuUserService service = new YihuUserService();

	@RequestMapping(value = "/qrcode", method = RequestMethod.POST)
	public @ResponseBody Object add(@RequestBody QRCode code) {
		// 新增二维码记录
		Object o = service.addQrCode(code);
		if(o==null){
			return getResult(1, "This provide id is exsit!");
		}
		code = (QRCode)o;
		Osslog.info("code.id" + code.getId());
		String qrid = code.getId()+","+code.getProvideId();
		// 生成二维码图像
		String filePath = request.getSession().getServletContext().getRealPath("/") + "images/wxlogo.JPG";
		String url = "http://www.yihuyixi.com/wxservice/receive?qrid=" + qrid; // wx																					// auth2.0
		BufferedImage image = QRCodeUtil.getLogoQRCode(url, "", filePath,1);
		byte[] datas = null;
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ImageIO.write(image, "png", out);
			datas = out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} // TODO
			// 将二维码图片插入mongo数据库
		service.addQrCodeOfCoupon(code, datas);
		return getResult(0, null);
	}
	
	/***
	 * 新增群组活动，因为多个人共享一个活动。分两步，1创建活动记录
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/qrcode/group1", method = RequestMethod.POST)
	public @ResponseBody Object addQrcode1(@RequestBody QRCode code) {
		// 新增二维码记录
		Osslog.info("/qrcode/group" + code);
		Object o = service.addQrCode(code);
		if(o==null){
			return getResult(1, "This provide id is exsit!");
		}
		return getResult(0, null);
	}
	/***
	 * 第二步，生成二维码
	 * @param 
	 * id:objectid   
	 * provideId:发布人id,写进publishid
	 * @return
	 */
	@RequestMapping(value = "/qrcode/group2", method = RequestMethod.POST)
	public @ResponseBody Object addQrcode2(@RequestBody QRCode code) {
		Osslog.info("addQrcode2" + code);
		long provideId = code.getProvideId();
		String codeId = code.getId();
		code = (QRCode)service.getQrCode(codeId);
		code.setProvideId(provideId);
		if(code.getGridfsids()!=null){
			for(GridFsUser gu:code.getGridfsids()){
				if(gu.getUserid()==provideId){
					return getResult(0, null);
				}
			}
		}
		Osslog.info("/qrcode/group2" + code);
		// 生成二维码图像
		String filePath = request.getSession().getServletContext().getRealPath("/") + "images/wxlogo.JPG";
		String qrid = codeId+","+provideId;
		String url = "http://www.yihuyixi.com/wxservice/receive?qrid=" + qrid; // wx																						// auth2.0
		BufferedImage image = QRCodeUtil.getLogoQRCode(url, "", filePath,1);
		byte[] datas = null;
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ImageIO.write(image, "png", out);
			datas = out.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} // TODO
		return service.addQrCodeOfCoupon(code, datas);
	}

	/***
	 * 生成产品详情图片二维码
	 * @param response
	 * @param session
	 * @param a
	 */
	@RequestMapping(value = "/qrcode/artwork", method = RequestMethod.GET)
	public void artworkQrcode(HttpServletResponse response, HttpSession session, ArtworkQrcodeVO a) {
		Osslog.info("into qrcode add Artwork" + a.getAid()+" type："+a.getType()+" userId:"+a.getUserId());
		// 生成二维码图像
		String filePath = request.getSession().getServletContext().getRealPath("/") + "images/wxlogo.JPG";
		String url = "http://www.yihuyixi.com/wxservice/qrcode/artwork?id=" + a.getAid()+"&userId="+a.getUserId()+"&type="+a.getType(); // wx																						// auth2.0
		int w = 430;
		int h = 430;
		BufferedImage image = QRCodeUtil.getLogoQRCode(url, "", filePath, w, h,1);
		try {
			response.setContentType("image/png");
			response.setHeader("Cache-Control", "max-age=604800");
			response.addDateHeader("Expires", System.currentTimeMillis() + 604800*1000);
			OutputStream os = response.getOutputStream();
			ImageIO.write(image, "png", os);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/qrcode/{id}", method = RequestMethod.DELETE)
	public @ResponseBody Object delete(@PathVariable("id") String id) {
		return service.deleteQrCode(id);
	}

	@RequestMapping(value = "/qrcode/{id}", method = RequestMethod.PUT)
	public @ResponseBody Object update(@PathVariable("id") String id, @RequestBody QRCode code) {
		if (StringUtils.isNotBlank(id)) {
			code.setId(id);
		}
		return service.updateQrCode(code);
	}

	@RequestMapping(value = "/qrcode/{id}", method = RequestMethod.GET)
	public @ResponseBody Object getActivity(@PathVariable("id") String id) {
		return service.getQrCode(id);
	}

	@RequestMapping(value = "/qrcode/download/{id}", method = RequestMethod.GET)
	public void getQrcodePng(HttpServletResponse response, HttpSession session, @PathVariable("id") String id)
			throws Exception {
		byte[] datas = service.getQrcodeByGridfsid(id);
		Osslog.info("bytes: " + datas);
		InputStream buffin = new ByteArrayInputStream(datas);// 业务逻辑取得图片的byte[]
		ServletOutputStream sos = null;//
		try {
			BufferedImage img = ImageIO.read(buffin);
			// 禁止图像缓存。
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			sos = response.getOutputStream();
			ImageIO.write(img, "png", sos);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			buffin.close();
			sos.close();
		}

	}

	/***
	 * 二维码列表 , 
	 * @param query  
	 *  model:  1：普通用户（消费者）:特殊类型，传publishId(用户userId)
	 *          2:代理商用户                 :传provideId(用户userId)
	 *  
	 * @return
	 */
	@RequestMapping(value = "/qrcode/list", method = RequestMethod.GET)
	public @ResponseBody Object getActivities(QrCodeQuery query) {
		Osslog.debug("/qrcode/list: "+query);
		return service.getQrCodes(query);
	}
	
	/**
	 * 
	 * @param 
	 *   id
	 *   publishids
	 * @return
	 */
	@RequestMapping(value = "/qrcode/publishids", method = RequestMethod.POST)
	public @ResponseBody Object addPublishids(@RequestBody QRCode code) {
		Osslog.debug("resolveQrCode.addPublishids: " + code);
		return service.addPublishids(code);
	}
	
	/**
	 * 
	 * @param 
	 *   id
	 *   publishids
	 * @return
	 */
	@RequestMapping(value = "/qrcode/publishids", method = RequestMethod.DELETE)
	public @ResponseBody Object deletePublishids(@RequestBody QRCode code) {
		Osslog.debug("resolveQrCode.deletePublishids: " + code);
		return service.deletePublishids(code);
	}

	/**
	 * 
	 * @param id
	 *            二维码id
	 * @return
	 */
	@RequestMapping(value = "/qrcode/resolve", method = RequestMethod.GET)
	public @ResponseBody Object resolveQrCode(String id) {
		Osslog.debug("resolveQrCode.qrcode: " + id);
		QRCode code = (QRCode) service.getQrCode(id);
		return code;
	}

	/*
	 * @RequestMapping(value = "/qrcode/genarate") public void
	 * genarate(HttpServletResponse response, HttpSession session, QRCode code)
	 * throws Exception { String filePath =
	 * request.getSession().getServletContext().getRealPath("/") +
	 * "images/wxlogo.JPG"; OutputStream os = response.getOutputStream();
	 * GridFSDBFile gfs = null;//
	 * (GridFSDBFile)service.getQrcodeByGridfsid(String.valueOf(code.
	 * getProvideId())); if (gfs != null) gfs.writeTo(os); else { String url =
	 * PropertiesUtil.getInstance().getProperty("serverhost") +
	 * "/qrcode/resolve" + "?provideId=" + code.getProvideId() +
	 * "&provideTotal=" + code.getProvideTotal() + "&targetMobile=" +
	 * code.getTargetMobile() + "&desc=" + code.getDesc(); BufferedImage image =
	 * QRCodeUtil.getLogoQRCode(url, "【一虎一席茶席艺术平台】商城优惠券", filePath); File file =
	 * new File("D:/2weima/TDC-" + new Date().getTime() + "test.png");
	 * ImageIO.write(image, "png", file); // TODO
	 * service.addQrCodeOfCoupon(code, file);
	 * response.setContentType("image/png"); ImageIO.write(image, "png", os); }
	 * os.flush(); os.close(); }
	 */

}
